package com.woniu.map.remote;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSONObject;

import com.woniu.map.remote.url.YingYanUrl;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class YingYanServiceClient {

    /**
     * 创建服务
     */
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private YingYanUrl yingYanURL;


    public String addYingYanService(String name){


        String url = yingYanURL.buildAddYingYanService(name);
        log.info("创建服务：{}",url);
        ResponseEntity<String> forEntity = restTemplate.postForEntity(url, null,String.class);
        log.info("创建服务响应：{}",forEntity.getBody());
        return parseSid(forEntity.getBody());
    }

    private  String parseSid(String body) {
        if (StringUtils.isEmpty( body)){
            throw new IllegalArgumentException("响应失败");
        }

        JSONObject response = JSONObject.parseObject(body);
        if (!response.get("errcode").equals(10000)){
            throw new IllegalArgumentException("参数错误 或认证失败");
        }
        return response.getJSONObject("data").getString("sid");
    }

}
